﻿//
// Copyright (c) 2024 BPer
//

#include <bperwhip/BPerWhip.h>

#include <bperrtc/BPerRtcConnection.h>

#include <bperice/BPerRtcStun.h>
#include <bperice/BPerRtcSocket.h>

#include <bpersdp/BPerSdp.h>

#include <bperutil/sys/BPerLog.h>
#include <bperutil/sys/BPerCUrl.h>
#include <bperutil/sys/BPerCString.h>
#include <bperutil/sys/BPerHttp.h>

#define BPer_SDP_BUFFERLEN 1024*12

int32_t bPer_whip_getSignal(BPerRtcSession* session,char* url,char** premoteSdp,char* localSdp) {
	int32_t err=BPer_Ok;
	BPerUrlData urlData={0};
	bPer_http_url_parse(session->context.avinfo->sys.familyType,url,&urlData);

	char* remoteSdp=(char*)bPer_calloc(1,BPer_SDP_BUFFERLEN);

	if(bPer_http_post(BPerTrue,session->context.avinfo->sys.familyType,remoteSdp,urlData.server,
			urlData.port, urlData.stream, (uint8_t*)localSdp, bPer_strlen(localSdp))){
		char* endp=bPer_strstr(remoteSdp,"\r\n\r\n");
		if(endp) bPer_error("\n%s",endp+4);
		bPer_free(remoteSdp);
		return bPer_error_wrap(1,"query whip sdp failure!");
	}

	if(bPer_strstr(remoteSdp,"201")&&bPer_strstr(remoteSdp,"Created")){
		char* p2=bPer_strstr(remoteSdp,"\r\n\r\n");
		if(p2==NULL) return ERROR_RTC_Whip;
		char* p=bPer_strstr(p2,"v=0");
		if(p){
			int32_t len=bPer_strlen(p);
			char* sdp=(char*)bPer_calloc(len+1,1);
			bPer_cstr_replace(p,sdp, "\r\n", "\n");
			p=bPer_strstr(sdp,"\n\n");
			if(p) *p=0;
			*premoteSdp=sdp;
			err=BPer_Ok;
		}
	}else{
		err=ERROR_RTC_Whip;
	}
	return err;

}

int32_t bPer_whip_connectPeer(BPerRtcConnection* conn,char* url){
	BPerRtcSession* session=conn->session;
	int err=BPer_Ok;
	char* remoteSdp=NULL;


	char *localSdp=NULL;
	conn->createOffer(session, &localSdp);
	if(localSdp) conn->setLocalDescription(session,localSdp);
	if ((err=bPer_whip_getSignal(conn->session,url,&remoteSdp,localSdp))  == BPer_Ok) {
		if(remoteSdp) conn->setRemoteDescription(conn->session,remoteSdp);
	}
	bPer_free(localSdp);
	bPer_free(remoteSdp);
    return err;
}
